<template>
    <a-form
        :form="form"
        class="login-form"
        @submit="handleSubmit"
    >
        <a-form-item>
            <a-input
                v-decorator="['username',{rules: [{required: true,message: '请输入账号'}]}]"
                placeholder="账号"
            >
                <a-icon slot="prefix" type="user" style="color: rgba(0, 0, 0, 0.25)" />
            </a-input>
        </a-form-item>
        <a-form-item>
            <a-input
                v-decorator="['password',{rules: [{required: true,message: '请输入密码'}]}]"
                type="password"
                placeholder="密码"
            >
                <a-icon slot="prefix" type="lock" style="color: rgba(0, 0, 0, 0.25)" />
            </a-input>
        </a-form-item>
        <a-form-item>
            <a-button
                type="primary"
                html-type="submit"
                class="login-form-button"
            >
                登录
            </a-button>
        </a-form-item>
    </a-form>
</template>

<script>
import factory from "./factory";
export default {
    name: "Login",
    components: {},
    data() {
        return {
            // 表示当前为注册页面
            flag: true,
        };
    },
    beforeCreate() {
        this.form = this.$form.createForm(this, { name: "login-form" });
    },
    methods: {
        handleSubmit(e) {
            e.preventDefault();
            this.form.validateFields(async(err, values) => {
                if (err) return;
                const res = await factory.login(values);
                var data = res.data;
                // 登陆失败
                if (data.meta.status !== 200) {
                    return this.$message.error(data.meta.message);
                }
                // 登陆成功
                this.$message.success(data.meta.message);
                // 1．将登录成功之后的 token，保存到客户端的localStorage中，localStorage是持久化的存储机制，localStorage是会话期间的存储机制
                //   1.1项目中出了登录之外的其他API接口，必须在登录之后才能访问
                //   1.2 token只应在当前网站打开期间生效，所以将 token保存在localStorage中
                window.localStorage.setItem("token", data.data.token);
                // 2．通过编程式导航跳转到后台主页，路由地址是/home
                this.$router.push("/home");
                window.localStorage.setItem("currentMenu", "首页");
            });
        }
    },
};
</script>

<style scoped lang='less'>
.login-form {
    .login-form-button {
        width: 100%;
        height: 40px;
    }
    :deep(.ant-input){
        height: 40px;
    }
    :deep(.ant-form-item){
        &:last-of-type{
            margin-bottom: 0;
        }
    }
}
</style>
